import React, { useState, useEffect, useRef } from 'react'
import { List, Avatar, Space, Button, Divider, Form, message, Modal } from 'antd'
import { MessageOutlined, LikeOutlined, StarOutlined } from '@ant-design/icons'
import { getPostDetail, queryReplyList, essentialPost, deletePost, deleteReply } from '~/api/qa-api'
import { HeaderWrapper, LeftItemWrappr, RightItemWrapper, ItemWrapperContent } from './style'
import RichTextModal from '../rich-text-modal'
import { useNavigate, useLocation } from 'react-router-dom'
import { formatTime } from '~/utils/utils'
import 'braft-editor/dist/output.css'

const userInfo = JSON.parse(localStorage.getItem('u')!)
const ItemWrapper = ({ setVisible, index, detailData, refReplyId, setImgUrl, setImgPreview, deleteRow }: any) => {
  const {
    replyContent,
    replyContentHtml,
    replyDepartmentCode,
    replyDepartmentName,
    replyTime,
    replyUserName,
    replyUserNo,
    replyUserRole,
    updateTime,
    id,
    createUserRole,
    createDepartmentName,
    createUserName,
    createUserNo,
    createTime,
    postContentHtml,
  } = detailData
  const navigate = useNavigate()
  const isOriginalPoster = index === -1

  const onclickItem = (e: any) => {
    if (e.target.nodeName === 'IMG') {
      setImgUrl(e.target.currentSrc)
      setImgPreview(true)
    }
  }

  return (
    <ItemWrapperContent>
      <LeftItemWrappr>
        <div>
          <span>姓名:</span>
          <span>{isOriginalPoster ? createUserName : replyUserName}</span>
        </div>
        <div>
          <span>警号:</span>
          <span>{isOriginalPoster ? createUserNo : replyUserNo}</span>
        </div>
        <div>
          <span>角色:</span>
          <span>{isOriginalPoster ? createUserRole : replyUserRole}</span>
        </div>
        <div>
          <span>部门:</span>
          <span>{isOriginalPoster ? createDepartmentName : replyDepartmentName}</span>
        </div>
        {isOriginalPoster && <div className="louzhu">楼主</div>}
      </LeftItemWrappr>
      <RightItemWrapper>
        <div
          className="braft-output-content"
          dangerouslySetInnerHTML={{ __html: isOriginalPoster ? postContentHtml : replyContentHtml }}
          onClick={onclickItem}
        />
        <div>
          <span>
            {index + 2}楼 {formatTime(isOriginalPoster ? createTime : replyTime)}
          </span>
          <a
            onClick={() => {
              setVisible(true)
              refReplyId.current = id
            }}
            style={{ marginLeft: 10 }}
          >
            回复
          </a>
          {((isOriginalPoster ? createUserNo : replyUserNo) === userInfo.userNo || userInfo.roles.includes('ADMIN') || userInfo.roles.includes('POST_ADMIN')) && (
            <a
              onClick={() => {
                deleteRow(isOriginalPoster, id)
              }}
              style={{ marginLeft: 10 }}
            >
              删除
            </a>
          )}
        </div>
      </RightItemWrapper>
    </ItemWrapperContent>
  )
}

const ItemDetail = () => {
  const [visible, setVisible] = useState(false)
  const [detailData, setDetailData] = useState<any>({})
  const [listData, setListData] = useState([])
  const navigate = useNavigate()
  const { state }: any = useLocation()
  const [form] = Form.useForm()
  const refReplyId = useRef(0)
  const [imgUrl, setImgUrl] = useState()
  const [imgPreview, setImgPreview] = useState(false)

  const fetchQueryReplyList = async () => {
    const result = await queryReplyList({ postId: state.postId })
    setListData(result.data)
  }

  const fetchQaDetail = async () => {
    const { data } = await getPostDetail({ postId: state.postId })
    setDetailData(data)
    fetchQueryReplyList()
  }

  const deleteRow = async (isOriginalPoster: boolean, id: any) => {
    const api = isOriginalPoster ? deletePost : deleteReply
    const params = isOriginalPoster ? { postId: id } : { replyId: id }
    api(params).then(() => {
      message.success('删除成功')
      if (isOriginalPoster) {
        navigate('/qa')
      } else {
        fetchQueryReplyList()
      }
    })
  }

  const onClickEssentialPost = async () => {
    await essentialPost({ isEssential: isEssential ? 0 : 1, postId: state.postId })
    message.success('设置成功')
  }

  useEffect(() => {
    fetchQaDetail()
  }, [])

  const { postTitle, isEssential, caseNo } = detailData

  return (
    <div>
      <HeaderWrapper>
        <div>
          <span>标题：{postTitle}</span>
          <span style={{marginLeft: '20px'}}>序号：{state.rank + 1}</span>
          {caseNo && (<span style={{marginLeft: '20px'}}>案件编号：{caseNo}</span>)}
        </div>
        <div>
          <Button
            onClick={() => {
              navigate(`/qa?page=${state.current}`)
            }}
            type="primary"
          >
            返回专栏首页
          </Button>
          <Button
            onClick={() => {
              setVisible(true)
              refReplyId.current = 0
            }}
            style={{ marginLeft: 10 }}
            type="primary"
          >
            我要回复
          </Button>
        </div>
      </HeaderWrapper>
      <Divider style={{ margin: '5px 0px' }} />
      <ItemWrapper
        setImgPreview={setImgPreview}
        setImgUrl={setImgUrl}
        refReplyId={refReplyId}
        detailData={detailData}
        setVisible={setVisible}
        deleteRow={deleteRow}
        index={-1}
        key={-1}
      />
      <Divider style={{ margin: '5px 0px' }} />
      <List
        itemLayout="vertical"
        size="large"
        dataSource={listData}
        renderItem={(item: any, index) => {
          return (
            <>
              <ItemWrapper
                refReplyId={refReplyId}
                detailData={item}
                setVisible={setVisible}
                index={index}
                key={index}
                setImgUrl={setImgUrl}
                setImgPreview={setImgPreview}
                deleteRow={deleteRow}
              />
              <Divider style={{ margin: '5px 0px' }} />
            </>
          )
        }}
      />
      <RichTextModal
        visible={visible}
        onCancel={() => {
          setVisible(false)
        }}
        form={form}
        fetchQueryReplyList={fetchQueryReplyList}
        postId={state.postId}
        refReplyId={refReplyId.current}
        isReply
      />
      <Modal
        visible={imgPreview}
        onCancel={() => {
          setImgPreview(false)
        }}
        footer={null}
        width="max-content"
      >
        <img style={{ width: '100%' }} src={imgUrl} />
      </Modal>
    </div>
  )
}

export default ItemDetail
